package cn.edu.zsc.blms.service.collection;

import cn.edu.zsc.blms.domain.Book;
import cn.edu.zsc.blms.domain.Reader;
import cn.edu.zsc.blms.exception.EntityNotExistException;
import cn.edu.zsc.blms.model.Borrowing;
import cn.edu.zsc.blms.service.IBookService;
import cn.edu.zsc.blms.service.IBorrowingService;
import cn.edu.zsc.blms.service.IReaderService;

import java.util.*;

public class BorrowingService extends BaseService<Borrowing> implements IBorrowingService {
    private static BorrowingService singleton;
    static BorrowingService borrowingService;
    private final BookService bookService;
    private final ReaderService readerService;
    private final Map<Integer, Borrowing> BOOK_LENDING = new HashMap<>();
    private BorrowingService(IBookService bookService, IReaderService readerService){
        this.bookService = (BookService) bookService;
        this.readerService = (ReaderService) readerService;
    }
    public static BorrowingService getSingleton(){
        if(singleton == null){
            singleton = new BorrowingService(BookService.getSingleton(),ReaderService.getSingleton());
        }
        return singleton;
    }
    public void borrow(){
        try{
            System.out.println("请输入图书的ID: ");
            Book book = bookService.getEntity();
            if(Book.Status.可出借 != book.status){
               System.out.println("该图书已借出!");
               return;
            }
            if(book.disabled){
                System.out.println("该图书已废弃!");
                return;
            }
            System.out.println("请输入读者的ID: ");
            Reader reader = readerService.getEntity();
            if(reader.disable){
                System.out.println("该读者已被禁用!");
                return;
            }
            Borrowing borrowing = new Borrowing(reader, book, new Date());
            DATA.put(borrowing.id,borrowing);
            BOOK_LENDING.put(borrowing.id,borrowing);
            System.out.println("图书借出成功! ");
        } catch (EntityNotExistException e){
            System.out.println(e.getMessage());
        }
    }
    @Override
    public void giveBack(){
        try{
            System.out.println("请输入图书的ID: ");
            Book book = bookService.getEntity();
            Borrowing borrowing = BOOK_LENDING.get(book.id);
            if(borrowing == null){
                System.out.println("该图书并未借出");
                return;
            }
            borrowing.returnTime = new Date();
            book.status = Book.Status.可出借;
            BOOK_LENDING.remove(book.id);
            System.out.println("图书归还成功! ");
        } catch (EntityNotExistException e){
            System.out.println(e.getMessage());
        }
    }
    @Override
    public void query(){
        System.out.println("按出借顺序显示当前正在出借的图书: ");
        Set<Borrowing> borrowings = new TreeSet<>(BOOK_LENDING.values());
        for(Borrowing borrowing : borrowings){
            System.out.println(borrowing);
        }
    }
}
